from django.core.paginator import Paginator
from django.template.context import RequestContext
from django.shortcuts import render_to_response
from kalapankki.settings import MEDIA_ROOT, ALBUM_PAGES_PER_VIEW
from kalapankki import settings
from kalapankki.album.models import Album
import random
import os
import string
import stat

def get_page_number(queryset, obj):
    for index, item in enumerate(queryset):
        if item == obj:
            return index/ALBUM_PAGES_PER_VIEW+1
    return 0
    
def handle_upload(up_file, up_dir, up_filename):
    #write the file to the users media folder
    path = os.path.join(settings.MEDIA_ROOT, up_dir)
    if not os.path.exists(path):
        os.makedirs(path)
        os.chmod(path, stat.S_IROTH | stat.S_IXOTH | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
    with open(os.path.join(path, up_filename), 'wb+') as destination:
        for chunk in up_file.chunks():
            destination.write(chunk)
    os.chmod(os.path.join(path, up_filename), stat.S_IROTH | stat.S_IXOTH | stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
    
def is_active_authenticated_user(request):
    return request.user and request.user.is_active and request.user.is_authenticated()
    
def get_pages(request, queryset, page_number=0):
    #make sure the value is an integer
    page_number = int(page_number)
    if page_number <= 0:
        #check if the request has a page number in query
        page_number = int(request.GET.get('page', 1))
    paginator = Paginator(queryset.all(),ALBUM_PAGES_PER_VIEW)
    #at this point the page_number is always 1 or larger so only check if it's too large
    if page_number <= paginator.num_pages:
        pages = paginator.page(page_number)
    else:
        #use negative numbers to point to the last page
        pages = paginator.page(paginator.num_pages)
    return pages

def render_with_request_context(request, template_name, context):
    return render_to_response(template_name, context, context_instance=RequestContext(request))

def generate_public_token(album):
    chars= string.ascii_letters + string.digits
    try:
        #could potentially loop forever in a huge dataset but for our case it is sufficient
        while True:
            #create a pseudorandom 32 char string to be used as the public token
            public_token = ''.join(random.choice(chars) for x in range(32))
            Album.objects.get(public_token = public_token)
    except Album.DoesNotExist:
        album.public_token = public_token

